﻿namespace WebDevUtilities.VsixPkg.Extensions.AspTemplateConverter
{
    using System;
    using System.ComponentModel;
    using System.Windows;
    using System.Windows.Controls;
    using EnvDTE;
    using EnvDTE80;
    using Microsoft.VisualStudio.Shell;
    using System.IO;
    using WebDevUtilities.Common.Enum;

    /// <summary>
    /// Interaction logic for ToolWindow.xaml
    /// </summary>
    public partial class ToolWindowControl : UserControl
    {
        private OutputWindowPane outputWP;
        private BackgroundWorker bgw;
        private DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
        EnvDTE.DTE dte = (EnvDTE.DTE)Package.GetGlobalService(typeof(EnvDTE.DTE));
        private EnvDTE.SelectionEvents dteSelectionEvents;
        OutputWindowPane owp;

        public void HandleNewFileSelection()
        {
            IsEnabled = CheckIfSelectedItemsAreValid(dte2);
        }

        private bool CheckIfSelectedItemsAreValid(DTE2 _dte2)
        {
            bool isValid = false;
            UIHierarchy solutionExplorer = _dte2.ToolWindows.SolutionExplorer;
            var items = solutionExplorer.SelectedItems as Array;
            if (items != null && items.Length != 0)
            {
                foreach (UIHierarchyItem hierarchyItem in items)
                {
                    ProjectItem prjItem = hierarchyItem.Object as ProjectItem;
                    FileInfo fileInfo = new FileInfo(prjItem.Properties.Item(Constants.ProjectItemPropertyFullPath).Value.ToString());
                    string fileTypeExt = fileInfo.Extension.ToLower();
                    switch (fileTypeExt)
                    {
                        case FileType.ASPX:
                        case FileType.ASCX:
                            isValid = true;
                            break;
                        default:
                            isValid = false;
                            break;
                    }
                }
                return isValid;
            }
            else return false;
        }

        public ToolWindowControl()
        {
            WebDevloperUtilitiesPackage package = new WebDevloperUtilitiesPackage();
            owp = package.WduOutputWindowPane;
            dteSelectionEvents = dte.Events.SelectionEvents;
            dteSelectionEvents.OnChange += new _dispSelectionEvents_OnChangeEventHandler(this.HandleNewFileSelection);
            IsEnabled = false;
            InitializeComponent();
        }

        private void StartASPTemplateConverterWorker()
        {
            if (bgw.IsBusy)
            {
                bgw.CancelAsync();
            }
            else
            {
                WorkerLogic controlConverterWorker = new WorkerLogic();
                controlConverterWorker.Dte = dte2;
                controlConverterWorker.RemovePrefixes = chkRemovePrefixes.IsChecked.Value;
                if (controlConverterWorker.RemovePrefixes)
                {
                    controlConverterWorker.Prefix = tbPrefix.Text;
                }
                controlConverterWorker.CopyImports = chkCopyImports.IsChecked.Value;
                controlConverterWorker.NameSpace = tbNamespace.Text;
                if (string.IsNullOrEmpty(tbBaseclass.Text))
                {
                    controlConverterWorker.UseDefaultBaseClass = true;
                    AddConsoleEntry(AspTemplateConverter.Resources.UsingDefaultBaseClass);
                }
                else
                {
                    controlConverterWorker.UseDefaultBaseClass = false;
                    controlConverterWorker.BaseClass = tbBaseclass.Text;
                }
                controlConverterWorker.OnWorkerOutput += new WorkerLogic.OnWorkerOutputDelegate(OnWorkerOutput);
                bgw.DoWork += new DoWorkEventHandler(controlConverterWorker.Worker);
                bgw.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
                bgw.RunWorkerAsync();
            }
        }
        
        private void OnWorkerOutput(string output)
        {
            AddConsoleEntry(output);
        }

        private void btnConvert_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StartASPTemplateConverterWorker();
            }
            catch (Exception ex)
            {
                AddConsoleEntry(AspTemplateConverter.Resources.UnknownError + " " + AspTemplateConverter.Resources.CheckOutputWindow + AspTemplateConverter.Resources.Error + ": '" + ex.Message + "'");
                MessageBox.Show(AspTemplateConverter.Resources.UnknownError + " " + AspTemplateConverter.Resources.CheckOutputWindow, AspTemplateConverter.Resources.Error, MessageBoxButton.OK, MessageBoxImage.Error);
                btnConvert.IsEnabled = true;
            }
        }

        void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            btnConvert.IsEnabled = true;
            if (e.Error != null)
            {
                OnWorkerOutput(string.Format(AspTemplateConverter.Resources.ProcessEndWithErrors, e.Error.Message));
            }
            else
            {
                if (e.Cancelled)
                {
                    OnWorkerOutput(AspTemplateConverter.Resources.ProcessCanceled);
                }
                else
                {
                    OnWorkerOutput(AspTemplateConverter.Resources.ConversionCompleted);
                }
            }
        }
        
        private void ToolWindow_Loaded(object sender, RoutedEventArgs e)
        {
            lblNamespace.Content = AspTemplateConverter.Resources.LblNamespaceContent;
            tbBaseclass.ToolTip = AspTemplateConverter.Resources.TbBaseclassToolTip;
            chkRemovePrefixes.Content = AspTemplateConverter.Resources.ChkRemovePrefixesContent;
            chkRemovePrefixes.ToolTip = AspTemplateConverter.Resources.ChkRemovePrefixesToolTip;
            chkCopyImports.Content = AspTemplateConverter.Resources.chkCopyImportsContent;
            chkCopyImports.ToolTip = AspTemplateConverter.Resources.chkCopyImportsToolTip;
            btnConvert.Content = AspTemplateConverter.Resources.BtnConvertContent;
            tbNamespace.ToolTip = AspTemplateConverter.Resources.TbNamespaceToolTip;
            checkEmptyNamespace();
            bgw = new BackgroundWorker();
        }

        private bool checkEmptyNamespace()
        {
            if (string.IsNullOrEmpty(tbNamespace.Text))
            {
                btnConvert.IsEnabled = false;
                return false;
            }
            else
            {
                btnConvert.IsEnabled = true;
                return true;
            }
        }

        public void AddConsoleEntry(string entry)
        {
            owp.OutputString(DateTime.Now + " " + AspTemplateConverter.Resources.ToolWindowTitle + ": " + entry + Environment.NewLine);
        }

        private void tbNamespace_TextChanged(object sender, TextChangedEventArgs e)
        {
            checkEmptyNamespace();
        }

        private void ControlConverterToolWindow_Initialized(object sender, EventArgs e)
        {
            AddConsoleEntry(AspTemplateConverter.Resources.ControlConverterInitialized);
        }
    }
}